package org.gten.gegedexin.IMAP;


import org.gten.gegedexin.IMAP.IMAP;

import java.io.IOException;
import java.util.ArrayList;

import static org.gten.gegedexin.service.ReceiveFile.FILEPATH;

public class IMAPClient {
    private IMAP imap = null;//IMAP协议对象

    /**无参构造函数*/
    public IMAPClient() {
        String server = "imap.qq.com";
        int port = 143;
        imap = new IMAP(server, port);
    }

    /**有参构造函数*/
    public IMAPClient(String server, int port) {
        imap = new IMAP(server, port);
    }

    /**IMAP的案例程序，并不是需要提供的接口，用于调试*/
    public boolean receiveMail(String user, String password) {
        try {
            //调用IMAP命令读取邮件
            //登陆邮箱服务器，LOGIN
            imap.login(user, password);
            imap.select("INBOX");
//            testFetchSubject();
//            Date date = fetchDate(14);
//            System.out.println("日期：" + date);
//            ArrayList<Integer> newEmails = searchNewEmail();
//            System.out.println("邮箱中的新邮件：\n" + newEmails);
//            fetchEmail(6);
//            fetchEmail(5);
            for (int i = 3; i < 4; ++i) {
                String body = imap.fetchEmail(i, FILEPATH+"resources/tempFile/");//获取正文并下载附件
                System.out.println("第" + i + "封邮件正文：\n" + body);
            }
            imap.logout();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**给后端提供的无参数接口*/
    public ArrayList<MailDigest> receiveUnseenMails() throws IOException {
        //登陆邮箱所需的信息
        String user = "2424654364@qq.com";
        String password = "ashbwgbuwikgdhhd";
        String folder = "INBOX";//默认邮箱文件夹和附件下载路径
        String destDir = FILEPATH+"resources/tempFile/";//使用相对路径存储到tempfile中
        imap.login(user, password);
        imap.select(folder);//选择文件夹后，读取所有未读文件
        ArrayList<Integer> unseenMails = imap.searchUnseenEmail();
        if (unseenMails == null)//如果邮箱中没有新邮件，那么返回null
        {
            imap.logout();
            return null;
        }
        ArrayList<MailDigest> mailDigests = new ArrayList<>();
        //有未读邮件，逐个读取
        for (Integer unseenMail : unseenMails) {
            MailDigest mailDigest = imap.fetchSingleAtmtEmail(unseenMail, destDir);
            mailDigests.add(mailDigest);
        }
        imap.logout();

        return mailDigests;
    }

    public static void main(String[] args) throws IOException {
        IMAPClient imapClient = new IMAPClient();
        imapClient.receiveUnseenMails();
    }
}
